<template>
  <div class="app-container">
    <!-- 搜索/筛选 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="是否绑定" prop="activeStatus">
        <el-select v-model="queryParams.bind" placeholder="全部" clearable style="width: 120px;">
          <el-option label="全部" :value="''" />
          <el-option label="绑定" value="1" />
          <el-option label="解绑" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名称" prop="name">
        <el-input v-model="queryParams.memberLinkName" placeholder="输入用户名" clearable @keyup.enter.native="handleQuery" style="width: 220px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" size="mini" @click="handleBatchMessage">群发消息</el-button>
        <el-button type="warning" size="mini" @click="handleViewMsgLog">查看消息记录</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="lqDataList" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="用户名称" prop="memberLinkName" />
      <el-table-column label="联系方式" prop="memberLinkPhone" />
      <el-table-column label="所属部门" prop="branchName" />
      <el-table-column label="绑定状态" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.bindTime">
              <el-tag type="success">已绑定</el-tag>
          </template>
          <el-tag v-else type="danger" size="small">
            未绑定
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绑定时间" prop="bindTime" />
      <el-table-column label="会员ID" prop="memberId"  />
      <!-- <el-table-column label="小程序ID" prop="miniAppId" min-width="120" /> -->
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="openBindDialog(scope.row)">绑定企业</el-button>
          <el-button type="danger" size="mini" @click="openViewDialog(scope.row)">查看企业</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（通用组件） -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 绑定企业弹框 -->
    <el-dialog title="绑定企业" :visible.sync="bindDialog.visible" width="90%" top="5vh" append-to-body>
      <!-- 搜索栏 -->
      <div style="display:flex; align-items:center; gap:12px; flex-wrap: wrap; margin-bottom: 16px;">
        <span style="font-weight:600; font-size:18px; margin-right: 16px; visibility:hidden;">占位</span>
        <span style="width:80px;">企业名称</span>
        <el-input v-model="bindDialog.query.companyName" placeholder="输入企业名称" clearable style="width: 240px;" />
        <span style="width:80px; margin-left: 8px;">企业类型</span>
        <el-select v-model="bindDialog.query.companyTypeId" placeholder="选择企业类型" clearable style="width: 240px;">
          <el-option v-for="opt in companyTypeOptions" :key="opt.id" :label="opt.typeName" :value="opt.id" />
        </el-select>
        <el-button type="primary" @click="fetchCompanyTypeList">搜索</el-button>
      </div>

      <!-- 企业列表 -->
      <el-table v-loading="bindDialog.loading" :data="bindDialog.list" height="55vh" @selection-change="onCompanySelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column prop="companyName" label="企业名称" min-width="280" />
        <el-table-column prop="companyType" label="企业类型" min-width="160" />
        <el-table-column prop="contact" label="联系人" min-width="120" />
        <el-table-column prop="contactPhone" label="联系电话" min-width="160" />
      </el-table>

      <!-- 弹框内分页 -->
      <div style="display:flex; align-items:center; justify-content:space-between; margin-top: 16px;">
        <span>共{{ bindDialog.total }}条</span>
        <pagination
          v-show="bindDialog.total > 0"
          :total="bindDialog.total"
          :page.sync="bindDialog.query.current"
          :limit.sync="bindDialog.query.size"
          @pagination="fetchCompanyTypeList"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bindDialog.visible = false">取 消</el-button>
        <el-button type="primary" :disabled="!bindDialog.selectedIds.length" @click="confirmBindCompany">确认绑定</el-button>
      </div>
    </el-dialog>

    <!-- 查看企业弹框 -->
    <el-dialog title="已绑定的企业" :visible.sync="viewDialog.visible" width="40%" top="8vh" append-to-body>
      <div style="display:flex; justify-content:flex-end; margin-bottom: 10px;">
        <el-button type="danger" :disabled="!viewDialog.selectedIds.length" @click="confirmUnbind">解绑企业</el-button>
      </div>
      <el-table v-loading="viewDialog.loading" :data="viewDialog.list" height="55vh"  stripe @selection-change="onViewSelectionChange">
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column prop="companyId" label="企业ID" align="center"/>
        <el-table-column prop="companyName" label="企业名称" align="center"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialog.visible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLqMember, companyTypeList, listCompany, linkCompany, getCompanysByBranchMember } from "@/api/biz/api";

export default {
  name: "LqUser",
  data() {
    return {
      loading: false,
      // 选中数组
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      lqDataList: [],
      queryParams: {
        current: 1,
        size: 50,
        bind: '', // active/inactive/''
        memberLinkName: ''
      },
      // 绑定企业弹框数据
      bindDialog: {
        visible: false,
        loading: false,
        list: [],
        total: 0,
        selectedIds: [],
        user: null,
        query: {
          current: 1,
          size: 10,
          companyName: '',
          companyTypeId: ''
        }
      },
      companyTypeOptions: [],
      // 查看企业弹框数据
      viewDialog: {
        visible: false,
        loading: false,
        list: [],
        selectedIds: [],
        user: null
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 列表数据
    getList() {
      this.loading = true;

      listLqMember(this.queryParams).then(({ data }) => {
        this.lqDataList = data.records || [];
        this.total = data.total || 0;
        this.loading = false;
      }).catch(() => { this.loading = false; });
    },
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = { current: 1, size: 50, bind: '', memberLinkName: '' };
      this.getList();
    },
    handleSelectionChange(selection) {
      this.ids = selection;
      this.multiple = !selection.length;
    },
    handleBatchMessage() {
      this.$modal.msg('TODO: 群发消息');
    },
    handleViewMsgLog() {
      this.$modal.msg('TODO: 消息记录');
    },
    // 打开绑定企业弹框
    openBindDialog(row) {
      console.log(' openBindDialog row is ', row);
      
      this.bindDialog.user = row.id;//row.memberId;【此处字段待确认】
      this.fetchCompanyTypeList();

      this.bindDialog.visible = true;
      this.bindDialog.query.current = 1;
    },
    // 打开查看企业弹框
    openViewDialog(row) {
      this.viewDialog.user = row.id;
      this.viewDialog.visible = true;
      this.fetchBoundCompanies();
    },
    // 获取企业类型列表
    fetchCompanyTypeList() {
      this.bindDialog.loading = true;

      companyTypeList()
        .then(({ data }) => {
          this.companyTypeOptions = data;
          this.bindDialog.loading = false;
        })
        .catch((error) => {
          console.error('获取企业类型列表失败:', error);
          this.bindDialog.loading = false;
        });

        listCompany({
        current: this.bindDialog.query.current,
        size: this.bindDialog.query.size,
        companyName: this.bindDialog.query.companyName,
        companyTypeId: this.bindDialog.query.companyTypeId
      }).then(({ data }) => {
        this.bindDialog.list = data.records || [];
        this.bindDialog.total = data.total || 0;
      });
    },
    onCompanySelectionChange(selection) {
      this.bindDialog.selectedIds = selection.map(s => s.id);
    },
    confirmBindCompany() {
      if (!this.bindDialog.selectedIds.length) {
        this.$modal.msgWarning('请选择要绑定的企业');
        return;
      }
      linkCompany({
        memberLinkId: this.bindDialog.user,
        companyIds: this.bindDialog.selectedIds,
        op: 1 // 1:绑定, 0:解绑
      }).then(() => {
        this.$modal.msgSuccess('绑定成功');
        this.bindDialog.visible = false;
      });

    },
    // 查看企业：加载当前用户已绑定企业
    fetchBoundCompanies() {
      this.viewDialog.loading = true;
      getCompanysByBranchMember(this.viewDialog.user).then(({ data }) => {
        this.viewDialog.list = data;
        this.viewDialog.loading = false;
      });
    },
    onViewSelectionChange(selection) {
      this.viewDialog.selectedIds = selection.map(s => s.companyId);
    },
    confirmUnbind() {
      if (!this.viewDialog.selectedIds.length) {
        this.$modal.msgWarning('请选择要解绑的企业');
        return;
      }
      this.$modal.confirm('确认解绑选中的企业吗？').then(() => {
        linkCompany({
          memberLinkId: this.viewDialog.user,
          companyIds: this.viewDialog.selectedIds,
          op: 0 // 1:绑定, 0:解绑
        }).then(() => {
          this.$modal.msgSuccess('解绑成功');
          this.viewDialog.visible = false;
          this.viewDialog.selectedIds = [];

          // this.fetchBoundCompanies();
        });
      }).catch(() => {});
    }
  }
};
</script>
